package com.peng.imdemo;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;

import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.PacketCollector;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.SmackConfiguration;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.filter.AndFilter;
import org.jivesoftware.smack.filter.PacketFilter;
import org.jivesoftware.smack.filter.PacketIDFilter;
import org.jivesoftware.smack.filter.PacketTypeFilter;
import org.jivesoftware.smack.packet.IQ;
import org.jivesoftware.smack.packet.Packet;
import org.jivesoftware.smack.packet.Presence;
import org.jivesoftware.smack.packet.Registration;
import org.jivesoftware.smack.util.StringUtils;

import java.util.Collection;

public class MainActivity extends AppCompatActivity {

    private static final String TAG = "MainActivity";

    private XMPPConnection connection;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void click(View view) {
        if (conServer()) {
            Log.d(TAG, "onCreate: " + register("user2", "123"));
        } else {
            Log.d(TAG, "click: " + "连接失败");
        }

        login("peng", "123");
    }

    /**
     * 连接服务器
     *
     * @return
     */
    public boolean conServer() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                ConnectionConfiguration config = new ConnectionConfiguration("192.168.1.36", 5222);
//                ConnectionConfiguration config = new ConnectionConfiguration("localhost", 5222);

                /** 是否启用调试 */
                // config.setDebuggerEnabled(true);

                /** 设置是否启用安全模式 */
                config.setSecurityMode(ConnectionConfiguration.SecurityMode.disabled);//设置为disabled

                /**
                 * 是否启用 SASL 安全验证
                 * Androidpn 默认还是使用了SASL认证，而我们不需要此认证
                 * 如果不关掉该认证，会报安全异常错误
                 *
                 */
                config.setSASLAuthenticationEnabled(false);
                config.setCompressionEnabled(false);

                /**
                 * 创建 connection 链接
                 */
                try {
                    connection = new XMPPConnection(config);
                    /**
                     * 建立连接，连接服务器
                     */
                    connection.connect();
                } catch (XMPPException e) {
                    e.printStackTrace();
                }
            }

        }).start();

        return true;
    }

    /**
     * 注册
     *
     * @param account  注册帐号
     * @param password 注册密码
     * @return 1、注册成功 0、服务器没有返回结果2、这个账号已经存在3、注册失败
     */
    public String register(String account, String password) {
        if (connection == null) {
            return "0";
        }
        Registration reg = new Registration();
        reg.setType(IQ.Type.SET);
        reg.setTo(connection.getServiceName());
        reg.setUsername(account);// 注意这里createAccount注册时，参数是username，不是jid，是“@”前面的部分。
        reg.setPassword(password);
        reg.addAttribute("android", "geolo_createUser_android");// 这边addAttribute不能为空，否则出错。所以做个标志是android手机创建的吧！！！！！
        PacketFilter filter = new AndFilter(new PacketIDFilter(reg.getPacketID()), new PacketTypeFilter(IQ.class));
        PacketCollector collector = connection.createPacketCollector(filter);
        connection.sendPacket(reg);
        IQ result = (IQ) collector.nextResult(SmackConfiguration.getPacketReplyTimeout());
        // Stop queuing results
        collector.cancel();// 停止请求results（是否成功的结果）
        if (result == null) {
            Log.e("RegistActivity", "No response from server.");
            return "0";
        } else if (result.getType() == IQ.Type.RESULT) {
            return "1";
        } else { // if (result.getType() == IQ.Type.ERROR)
            if (result.getError().toString().equalsIgnoreCase("conflict(409)")) {
                Log.e("RegistActivity", "IQ.Type.ERROR: "
                        + result.getError().toString());
                return "2";
            } else {
                Log.e("RegistActivity", "IQ.Type.ERROR: "
                        + result.getError().toString());
                return "3";
            }
        }
    }


    /**
     * 登录
     *
     * @param a 登录帐号
     * @param p 登录密码
     * @return
     */
    public boolean login(String a, String p) {
        try {
            if (connection == null)
                return false;
            /** 登录 */
            connection.login(a, p);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 修改密码
     *
     * @param connection
     * @return
     */
    public static boolean changePassword(XMPPConnection connection, String pwd) {
        try {
            connection.getAccountManager().changePassword(pwd);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 更改用户状态
     */
    public void setPresence(int code) {
        if (connection == null)
            return;
        Presence presence;
        switch (code) {
            case 0:
                presence = new Presence(Presence.Type.available);
                connection.sendPacket(presence);
                Log.v("state", "设置在线");
                break;
            case 1:
                presence = new Presence(Presence.Type.available);
                presence.setMode(Presence.Mode.chat);
                connection.sendPacket(presence);
                Log.v("state", "设置Q我吧");
                System.out.println(presence.toXML());
                break;
            case 2:
                presence = new Presence(Presence.Type.available);
                presence.setMode(Presence.Mode.dnd);
                connection.sendPacket(presence);
                Log.v("state", "设置忙碌");
                System.out.println(presence.toXML());
                break;
            case 3:
                presence = new Presence(Presence.Type.available);
                presence.setMode(Presence.Mode.away);
                connection.sendPacket(presence);
                Log.v("state", "设置离开");
                System.out.println(presence.toXML());
                break;
            case 4:
                Roster roster = connection.getRoster();
                Collection<RosterEntry> entries = roster.getEntries();
                for (RosterEntry entry : entries) {
                    presence = new Presence(Presence.Type.unavailable);
                    presence.setPacketID(Packet.ID_NOT_AVAILABLE);
                    presence.setFrom(connection.getUser());
                    presence.setTo(entry.getUser());
                    connection.sendPacket(presence);
                    System.out.println(presence.toXML());
                }
                // 向同一用户的其他客户端发送隐身状态
                presence = new Presence(Presence.Type.unavailable);
                presence.setPacketID(Packet.ID_NOT_AVAILABLE);
                presence.setFrom(connection.getUser());
                presence.setTo(StringUtils.parseBareAddress(connection.getUser()));
                connection.sendPacket(presence);
                Log.v("state", "设置隐身");
                break;
            case 5:
                presence = new Presence(Presence.Type.unavailable);
                connection.sendPacket(presence);
                Log.v("state", "设置离线");
                break;
            default:
                break;
        }
    }

    /**
     * 删除当前用户
     *
     * @param connection
     * @return
     */
    public static boolean deleteAccount(XMPPConnection connection) {
        try {
            connection.getAccountManager().deleteAccount();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
}
